package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceImpl;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;

import org.json.JSONException;
import org.json.JSONObject;

import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.dal.UserInfoDAL;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.User;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.ILoginService;

public class LoginService extends Service implements ILoginService {
    private final IBinder binder = new LocalBinder();
    private UserInfoDAL userInfoDAL;

    public class LocalBinder extends Binder {
        public LoginService getService() {
            return LoginService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        userInfoDAL = new UserInfoDAL(this);
    }

    public void setUserInfoDAL(UserInfoDAL userInfoDAL) {
        this.userInfoDAL = userInfoDAL;
    }

    @Override
    public Boolean register(User newUser) {
        return userInfoDAL.addUser(newUser) > 0;
    }

    @Override
    public JSONObject login(String username, String password) {
        JSONObject loginResult = new JSONObject();
        User userResult = userInfoDAL.login(username, password);

        try {
            if (userResult != null) {
                loginResult.put("success", Boolean.TRUE);
                loginResult.put("userId", userResult.getUserId());
                loginResult.put("email", userResult.getEmail());
                loginResult.put("role", userResult.getRole());
            } else {
                loginResult.put("success", Boolean.FALSE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return loginResult;
    }

    @Override
    public User getUserInfo(Integer userId) {
        return userInfoDAL.getUserInfoById(userId);
    }

    @Override
    public JSONObject updateUserInfo(User user) {
        JSONObject updateResult = new JSONObject();
        try {
            if (userInfoDAL.updateUserInfo(user) > 0) {
                updateResult.put("success", Boolean.TRUE);
                updateResult.put("newUserInfo", userInfoDAL.getUserInfoById(user.getUserId()));
            } else {
                updateResult.put("success", Boolean.FALSE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return updateResult;
    }
}
